package cn.qayy.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.qayy.constants.Constant;
import cn.qayy.dao.StandardMapper;
import cn.qayy.dto.BasisDTO;
import cn.qayy.dto.StandardDTO;
import cn.qayy.po.Basis;
import cn.qayy.po.Bid;
import cn.qayy.po.Policy;
import cn.qayy.po.Standard;
import cn.qayy.service.IPolicyService;
import cn.qayy.service.IStandardService;
import cn.qayy.service.Uploadable;
import cn.qayy.utils.DownLoadUtil;
import cn.qayy.utils.ServletContextUtils;
import cn.qayy.utils.StringUtil;

/***
 * @author wy
 *
 */
@SuppressWarnings("all")
@Service("standardServiceImpl")
public class StandardImpl implements IStandardService {
	private Logger logger = LoggerFactory.getLogger(StandardImpl.class);

	@Resource
	public StandardMapper standardMapper;
	
	@Resource(name = "policyServiceImpl")
	private IPolicyService policyService = null;

	@Override
	public int insertByList(List forList) throws Exception{
		updatePolicyByStandard(forList);
		return standardMapper.insertByList(forList);
	}

	@Override
	public PageInfo<Standard> selectStandardBy(Map<String, Object> params) throws Exception{
		if (params != null && params.size() > 0) {
			//下载时记住当时查询的条件
			DownLoadUtil.set("StandardDTO",params);
			PageHelper.startPage(StringUtil.parseInt(params.get("pageNumber").toString()), StringUtil.parseInt(params.get("pageSize").toString()));
			List<Standard> list = standardMapper.selectStandardBy(params);
			PageInfo<Standard> pageInfo = new PageInfo<Standard>(list);
			return pageInfo;
		}
		return null;
	}

	@Override
	public List<StandardDTO> selectStandardForDown(@RequestParam Map<String, Object> params) throws Exception{
		List<StandardDTO> list = standardMapper.selectStandardForDown(params);
		return list;
	}

	// @Override
	public int updateStandardByID(@RequestParam Map<String, Object> params)throws Exception {
		Standard standard = new Standard();
		standard.setId(Integer.parseInt(String.valueOf(params.get("id"))));
		standard.setProvince(params.get("province").toString());
		standard.setProduct(params.get("product").toString());
		standard.setPack(params.get("pack").toString());
		standard.setMode(params.get("mode").toString());
		standard.setZtype(params.get("ztype").toString());
		standard.setQudao(params.get("qudao").toString());
		standard.setBzcsj(params.get("bzcsj").toString());
		System.out.println("***:" + standard.toString());

		return standardMapper.updateByPrimaryKeySelective(standard);
	}

	@Override
	public Standard selectStandardByID(@RequestParam Integer standardId)throws Exception {
		return standardMapper.selectByPrimaryKey(standardId);
	}

	// @Override
	public int addStandard(@RequestParam Map<String, Object> params)throws Exception {
		Standard standard = new Standard();
		standard.setProvince(params.get("province").toString());
		standard.setProduct(params.get("product").toString());
		standard.setPack(params.get("pack").toString());
		standard.setMode(params.get("mode").toString());
		standard.setZtype(params.get("ztype").toString());
		standard.setQudao(params.get("qudao").toString());
		standard.setBzcsj(params.get("bzcsj").toString());
		System.out.println("***:" + standard.toString());

		return standardMapper.insertSelective(standard);
	}

	@Override
	public List<? extends String> selectPbKeys() throws Exception{
		return standardMapper.selectPbKeys();
	}

	/**
	 * 标测库同步更新协议 
	 * 标测库、中标库 和协议是一体的，匹配更新时协议时间取值范围：开始时间<=x<=结束时间。
	 * @param list
	 * @throws Exception
	 */
	private void updatePolicyByStandard(List list) throws Exception {
		for (Object obj : list) {
			Standard p = (Standard)obj;
			Map<String,Object> params = new HashMap<String,Object>();
			Set<String> provinces = new HashSet<String>();//省份
			Set<String> products = new HashSet<String>();//品种
			Set<String> packs = new HashSet<String>();//包装
			Set<String> modes = new HashSet<String>();//模式
			Set<String> ztypes = new HashSet<String>();//渠道
			Set<String> txs = new HashSet<String>();//条线
			
			//只更新4状态5状态6状态的协议
			Set<String> status = new HashSet<String>();
			status.add("4");
			status.add("5");
			status.add("6");
			params.put("status", status);
			//省份
			if(StringUtil.isNotBlank(p.getProvince())) {
				provinces.add(p.getProvince());
				params.put("provinces", provinces);
			}
			//品种
			if(StringUtil.isNotBlank(p.getProduct())) {
				products.add(p.getProduct());
				params.put("products", products);
			}
			//包装
			if(StringUtil.isNotBlank(p.getPack())) {
				packs.add(p.getPack());
				params.put("packs", packs);
			}
			//模式
			if(StringUtil.isNotBlank(p.getMode())) {
				modes.add(p.getMode());
				params.put("modes",modes);
			}
			//渠道
			if(StringUtil.isNotBlank(p.getZtype())) {
				ztypes.add(p.getZtype());
				params.put("ztypes",ztypes);
			}
			if(StringUtil.isNotBlank(p.getStime())) {
				params.put("stime", p.getStime());//开始时间
			}
			if(StringUtil.isNotBlank(p.getEtime())) {
				params.put("etime", p.getEtime());//结束时间
			}
			//根据中标库参数获取协议
			List<Policy> selectPolicys = policyService.selectPolicys(params);
			//System.out.println("size="+selectPolicys.size());
			//若获取到了则匹配
			if(selectPolicys != null && !selectPolicys.isEmpty()) {
				for(Policy po:selectPolicys) {
					po.setBiaozhuncsdj(p.getBzcsj());
				}
				//更新协议
				policyService.updateByList(selectPolicys);
				//协议更新后，同步更新流向
				policyService.updatePlansByPolicys(selectPolicys);
			} 
		}
	}
	@Override
	public int updateByList(List list) throws Exception{
		updatePolicyByStandard(list);
		return standardMapper.updateByList(list);
	}

	@Override
	public int deleteByList(List list) throws Exception {
		return standardMapper.deleteByList(list);
	}

	@Override
	public int insert(Object bean) throws Exception{
		return standardMapper.insert(bean);
	}

	@Override
	public int update(Object bean)throws Exception {
		return standardMapper.update(bean);
	}

	@Override
	public int delete(Object bean) throws Exception{
		return standardMapper.delete(bean);
	}

	@Override
	public Standard getStandard(Map<String,Object> params)throws Exception {
		return standardMapper.getStandard(params);
	}

	@Override
	public List<Standard> selectByMap(Map<String, Object> params) {
		return standardMapper.selectByMap(params);
	}

	@Override
	public List<Integer> selectIdsByMap(Map<String, Object> params) {
		return standardMapper.selectIdsByMap(params);
	}

	@Override
	public void persistence(Map<String, List<Uploadable>> map, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		List<Uploadable> listE = map.get("E");
		List<Standard> plist = new ArrayList<Standard>();
		
		if(listE!=null && !listE.isEmpty()) {
			List<Standard> db_list = new ArrayList<Standard>(listE.size()+1);
			List<String> ids = new ArrayList<String>(listE.size()+1);
			for (Uploadable u : listE) {
				StandardDTO dto = (StandardDTO)u;
				ids.add(dto.getId());
			}
			
			db_list = standardMapper.selectByIds(ids);
			//校验Excel上传的id是否正确
			if(ids.size() != db_list.size()) {
				throw new Exception(Constant.FAIL_MSG_ID);
			}
			
			// 待更新的实体list
			List<Standard> list = new ArrayList<Standard>(listE.size()+1);
			for (Uploadable u : listE) {
				StandardDTO dto = (StandardDTO)u;
				for(Standard s:db_list) {
					if(s.getId().toString().equals(dto.getId())) {
						plist.add(s);
						s.setByDTO(dto);
						list.add(s);
						continue;
					}
				}
			}
			if(!list.isEmpty()) {
				removeToContext(plist);
				try {
					standardMapper.updateByList(list);
				} catch (Exception e) {
					addToContext(plist);
					throw e;
				}
				//同步更新协议
				updatePolicyByStandard(list);
				//添加到缓存
				addToContext(list);
			}
		}
		List<Uploadable> listN = map.get("N");
		if(listN!=null && !listN.isEmpty()) {
			//待新增的实体list
			List<Standard> list = new ArrayList<Standard>(listN.size()+1);
			for (Uploadable u : listN) {
				StandardDTO dto = (StandardDTO)u;
				//封装数据
				Standard s = new Standard();
				s.setByDTO(dto);
				list.add(s);
			}
			if(!list.isEmpty()) {
				standardMapper.insertByList(list);
				//同步更新协议
				updatePolicyByStandard(list);
				//添加到缓存
				addToContext(list);
			}
		}
	}
	
	/***
     * 持久化中标库后，更新context缓存
     * @param list
     */
    private void addToContext(List<Standard> list) {
    	/***
    	 * 获取项目上下文的共享数据
    	 */
    	ServletContext servletContext = ServletContextUtils.getServletContext();
    	//标准测算价keys
    	Set<String> pbKeys = (Set<String>)servletContext.getAttribute("pbKeys");
		for (Standard b : list) {
			pbKeys.add(StringUtil.concat(b.getProvince(),b.getProduct(),b.getPack(),b.getMode(),b.getQudao(),b.getZtype(),b.getStime(),b.getEtime(),b.getId()+""));
		}
    }
    /***
     * 持久化中标库后，更新context缓存
     * @param list
     */
    private void removeToContext(List<Standard> list) {
    	/***
    	 * 获取项目上下文的共享数据
    	 */
    	ServletContext servletContext = ServletContextUtils.getServletContext();
    	//标准测算价keys
    	Set<String> pbKeys = (Set<String>)servletContext.getAttribute("pbKeys");
    	for (Standard b : list) {
    		pbKeys.remove(StringUtil.concat(b.getProvince(),b.getProduct(),b.getPack(),b.getMode(),b.getQudao(),b.getZtype(),b.getStime(),b.getEtime(),b.getId()+""));
    	}
    }
}
